<template>
  <Dialog v-model="dialogVisible" title="回访内容" width="900">
    <!-- 计划信息 -->
    <el-card class="plan-info-card mb-15px" shadow="hover" :body-style="{ padding: '16px' }">
      <div class="flex items-center justify-between">
        <div class="info-item">
          <span class="info-label">计划：</span>
          <span class="info-value">{{ planInfo.name }}</span>
        </div>
        <div class="info-item">
          <span class="info-label">客户：</span>
          <span class="info-value">{{ planInfo.customerName }}</span>
        </div>
        <div class="info-item">
          <span class="info-label">负责人：</span>
          <span class="info-value">{{ planInfo.principalName }}</span>
        </div>
      </div>
    </el-card>

    <!-- 回访记录列表 -->
    <div v-loading="loading" class="records-container">
      <div v-for="(group, index) in groupedList" :key="index" class="record-item">
        <div class="record-header">
          <div class="record-date">{{ formatDateTime(group.createTime) }}</div>
          <div class="record-actions">
            <el-button link type="primary" size="small" @click="handleEdit(group)">
              <el-icon class="mr-5px"><Edit /></el-icon>编辑
            </el-button>
            <el-button link type="danger" size="small" @click="handleDelete(group.id)">
              <el-icon class="mr-5px"><Delete /></el-icon>删除
            </el-button>
          </div>
        </div>
        <el-card class="record-content" shadow="hover">
          <div class="record-text">{{ group.content }}</div>
          <div class="record-meta">
            <span>回访人：{{ group.followUpUserName }}</span>
            <el-divider direction="vertical" />
            <span>回访时间：{{ formatFollowUpTime(group.followUpTime) }}</span>
          </div>
        </el-card>
      </div>

      <!-- 无数据提示 -->
      <el-empty description="暂无回访记录" v-if="groupedList.length === 0" />
    </div>

    <!-- 添加回访记录表单 -->
    <el-divider content-position="left">
      <span class="form-title">添加新的回访记录</span>
    </el-divider>

    <el-card shadow="hover" class="form-card">
      <el-form :model="formData" :rules="formRules" ref="formRef" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="回访人" prop="followUpUser">
              <el-select
                v-model="formData.followUpUser"
                clearable
                filterable
                placeholder="请选择回访人"
                style="width: 100%"
              >
                <el-option
                  v-for="item in userList"
                  :key="item.id"
                  :label="item.nickname"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="回访时间" prop="followUpTime">
              <el-date-picker
                v-model="formData.followUpTime"
                type="datetime"
                value-format="x"
                placeholder="选择回访时间"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="回访内容" prop="content">
          <el-input
            v-model="formData.content"
            type="textarea"
            :rows="4"
            placeholder="请输入回访内容"
          />
        </el-form-item>
        <el-form-item>
          <div class="text-right">
            <el-button type="primary" @click="submitForm" :loading="submitting">提 交</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-card>
  </Dialog>
</template>

<script setup lang="ts">
import { dateFormatter2 } from '@/utils/formatTime'
import {
  CustomerFollowUpContentApi,
  CustomerFollowUpContentVO
} from '@/api/erp/customer/followupcontent'
import { CustomerFollowUpPlanApi } from '@/api/erp/customer/followupplan'
import * as UserApi from '@/api/system/user'
import { UserVO } from '@/api/system/user'
import { Edit, Delete } from '@element-plus/icons-vue'

defineOptions({ name: 'CustomerFollowUpRecordDialog' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const loading = ref(false) // 列表的加载中
const submitting = ref(false) // 提交表单的加载中
const list = ref<CustomerFollowUpContentVO[]>([]) // 列表的数据
const planId = ref<number>() // 计划ID
const planInfo = ref<any>({}) // 计划信息
const userList = ref<UserVO[]>([]) // 用户列表
// 按日期分组的列表数据
const groupedList = computed(() => {
  if (!list.value || list.value.length === 0) return []

  // 为每条记录添加用户名称
  const processedList = list.value.map((item) => {
    const user = userList.value.find((u) => u.id === Number(item.followUpUser))
    return {
      ...item,
      followUpUserName: user ? user.nickname : item.followUpUser,
      // 确保有createTime字段，如果后端返回的数据中没有，则使用followUpTime作为备选
      createTime: (item as any).createTime || item.followUpTime
    }
  })

  // 按创建时间分组
  return processedList.sort((a, b) => Number(b.createTime) - Number(a.createTime))
})

// 表单数据
const formData = ref<{
  planId: number | undefined
  id?: number
  content: string
  followUpUser: number | undefined
  followUpTime: number | undefined
}>({
  planId: undefined,
  id: undefined,
  content: '',
  followUpUser: undefined,
  followUpTime: undefined
})

// 表单校验规则
const formRules = reactive({
  content: [{ required: true, message: '回访内容不能为空', trigger: 'blur' }],
  followUpTime: [{ required: true, message: '回访时间不能为空', trigger: 'blur' }],
  followUpUser: [{ required: true, message: '回访人不能为空', trigger: 'blur' }]
})

const formRef = ref() // 表单 Ref

// 格式化日期时间
const formatDateTime = (timestamp: string | number) => {
  if (!timestamp) return ''
  const date = new Date(Number(timestamp))
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

// 格式化回访时间
const formatFollowUpTime = (timestamp: string | number) => {
  return dateFormatter2(undefined as any, undefined as any, timestamp)
}

/** 查询列表 */
const getList = async () => {
  if (!planId.value) return
  loading.value = true
  try {
    const params = {
      planId: planId.value
    }
    const data = await CustomerFollowUpContentApi.getCustomerFollowUpContentPage(params)
    list.value = data || []
  } finally {
    loading.value = false
  }
}

/** 获取计划详情 */
const getPlanInfo = async () => {
  if (!planId.value) return
  try {
    planInfo.value = await CustomerFollowUpPlanApi.getCustomerFollowUpPlan(planId.value)
  } catch (error) {
    console.error('获取计划详情失败', error)
  }
}

/** 编辑回访记录 */
const handleEdit = (group: any) => {
  // 如果是组，则取第一个项目进行编辑
  const item = group.items ? group.items[0] : group
  formData.value = {
    id: item.id,
    planId: item.planId,
    content: item.content,
    followUpUser: Number(item.followUpUser), // 确保followUpUser是数字类型
    followUpTime: item.followUpTime
  }
  // 添加id用于更新
  formData.value.id = item.id
}

/** 删除回访记录 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await CustomerFollowUpContentApi.deleteCustomerFollowUpContent(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 提交表单 */
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()

  // 设置计划ID
  formData.value.planId = planId.value

  // 提交请求
  submitting.value = true
  try {
    const data = formData.value as any
    if (data.id) {
      // 更新
      await CustomerFollowUpContentApi.updateCustomerFollowUpContent(data)
      message.success(t('common.updateSuccess'))
    } else {
      // 新增
      await CustomerFollowUpContentApi.createCustomerFollowUpContent(data)
      message.success(t('common.createSuccess'))
    }

    // 重置表单
    resetForm()

    // 刷新列表
    await getList()
  } finally {
    submitting.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    planId: planId.value,
    content: '',
    followUpUser: undefined,
    followUpTime: undefined
  }
  // 确保id字段被删除，而不是设置为undefined
  if ('id' in formData.value) {
    delete (formData.value as any).id
  }
  formRef.value?.resetFields()
}

/** 打开弹窗 */
const open = async (id: number) => {
  dialogVisible.value = true
  planId.value = id
  resetForm()

  // 获取用户列表
  if (userList.value.length === 0) {
    userList.value = await UserApi.getSimpleUserList()
  }

  // 获取计划详情
  await getPlanInfo()

  // 获取回访记录列表
  await getList()
}

defineExpose({ open }) // 提供 open 方法，用于打开弹窗
</script>

<style scoped>
/* 计划信息卡片样式 */
.plan-info-card {
  transition: all 0.3s ease;
}

.plan-info-card:hover {
  transform: translateY(-2px);
}

.info-item {
  display: flex;
  align-items: center;
  margin-right: 15px;
}

.info-label {
  margin-right: 5px;
  font-weight: bold;
  color: var(--el-text-color-secondary);
}

.info-value {
  color: var(--el-color-primary);
}

/* 记录列表样式 */
.records-container {
  margin-bottom: 20px;
}

.record-item {
  margin-bottom: 15px;
  transition: all 0.3s ease;
}

.record-header {
  display: flex;
  padding: 0 5px;
  margin-bottom: 8px;
  align-items: center;
  justify-content: space-between;
}

.record-date {
  font-weight: bold;
  color: var(--el-color-primary);
}

.record-actions {
  display: flex;
  gap: 8px;
}

.record-content {
  border-radius: 6px;
  transition: all 0.3s ease;
}

.record-content:hover {
  transform: translateY(-2px);
}

.record-text {
  margin-bottom: 10px;
  line-height: 1.5;
  white-space: pre-wrap;
}

.record-meta {
  display: flex;
  font-size: 13px;
  color: var(--el-text-color-secondary);
  align-items: center;
}

/* 表单样式 */
.form-title {
  font-size: 16px;
  font-weight: bold;
  color: var(--el-text-color-primary);
}

.form-card {
  margin-top: 15px;
  transition: all 0.3s ease;
}

.field-equal-width {
  width: 100%;
  min-width: 240px;
}

/* 添加Element Plus组件样式覆盖 */
:deep(.el-card__body) {
  padding: 15px;
}

:deep(.el-divider__text) {
  background-color: var(--el-bg-color);
}

:deep(.el-button) {
  transition: all 0.3s ease;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}
</style>
